const {
	log
} = require("console")
const db = uniCloud.database()
const dbCmd = db.command
module.exports = {
	_before: function() {},
	async QBPay(list = [], user_id, address = {}, total = 0) {
		const transaction = await db.starTransaction()
		try {
			let userRes = await transaction.collection('uni-id-users').doc.(user_id).get()
			if (userRes.data) {
				const updateUserMoney = await transaction.collection('uni-id-users').doc.(user_id).update({
					money: dbCmd.inc(-total)
				})
				const addOrder = await transaction.collection('order').add({
					type: "商品订单",
					pay_type: "QB",
					total_fee: total,
					user_id: user_id,
					platform: "h5",
					status: 2,
					wait_status: 1,
					address: address,
					goods_list: list,
					create_time: time,
					update_time: time,
					paid_time: time
				})
				const updateUserRes = await transaction.collection('uni-id-users').doc.(user_id).get()
				if (updateUserRes.data.money < 0) {
					await transaction.rollback(-100)
					return {
						success: false,
						error: `rollback`,
						rollbackCode: -100,
					}
				} else {
					await transaction.commit()
				}
				return {
					success: true

				}
			} else {
				await transaction.rollback()
				return {
					success: false,
					error: `rollback`,
					rollbackCode: -100,
				}
			}
		} catch (e) {
			await transaction.rollback()
			return {
				success: false,
				error: e
			}
		}
	}
}
